package za.ac.wits.elen4010.capturetheflag;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

// TODO: Auto-generated Javadoc
/**
 * The Class ParsingHandler.
 */
public class ParsingHandler {
	
	/** The _http client. */
	private HttpClient _httpClient = null;
	
	/** The _dbf. */
	private DocumentBuilderFactory _dbf = null;
	
	/** The _db. */
	private DocumentBuilder _db = null;
	
	/**
	 * Instantiates a new parsing handler.
	 */
	public ParsingHandler()
	{
		_httpClient = new DefaultHttpClient();
		_dbf = DocumentBuilderFactory.newInstance();
		try
		{
			_db = _dbf.newDocumentBuilder();
		}
		catch(ParserConfigurationException pce)
		{
			//alert dialog
		}
	}
	
	/**
	 * Manage query.
	 *
	 * @param query the query
	 * @return the document
	 */
	public Document ManageQuery(String query)
	{
		HttpEntity streamEntity = executeQuery(query);
		Document parsedDoc = parseEntity(streamEntity);
		return parsedDoc;
	}
	
	/**
	 * Execute query.
	 *
	 * @param query the query
	 * @return the http entity
	 */
	@SuppressWarnings("finally")
	private HttpEntity executeQuery(String query)
	{
		HttpGet getRequest = new HttpGet(query);
		HttpEntity responseEntity = null;
		try
		{
			HttpResponse response = _httpClient.execute(getRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if(statusCode != HttpStatus.SC_OK)
			{
				//alert dialog
				return null;
			}
			
			responseEntity = response.getEntity();
		}
		catch(ClientProtocolException cpe)
		{
		}
		catch(IOException ioe)
		{
		}
		finally
		{	
			return responseEntity;
		}	
	}
	
	/**
	 * Parses the entity.
	 *
	 * @param entity the entity
	 * @return the document
	 */
	private Document parseEntity(HttpEntity entity)
	{
		try
		{
			InputStream is = entity.getContent();
			Document parsedDoc = _db.parse(is);
			return parsedDoc;
		}
		catch(IllegalStateException ise)
		{
			return null;
		}
		catch(SAXException saxe)
		{
			return null;
		}
		catch(IOException ioe)
		{
			return null;
		}
		finally
		{
		}
	}
}
